require('dotenv').config();

const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const multer = require('multer');
const cors = require('cors');
const os = require('os');  // 添加os模块用于系统信息获取

// JWT相关配置
const JWT_SECRET = process.env.JWT_SECRET || 'mydy_secret_key';
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '1d';

// 支持环境变量配置或默认值
const port = process.env.PORT || 3000;
const host = process.env.HOST || '0.0.0.0'; // 默认监听所有网络接口，便于宝塔面板访问

// 配置 CORS
const corsOptions = {
    origin: process.env.ALLOWED_ORIGINS || '*',
    methods: 'GET,POST,PUT,DELETE,OPTIONS',
    allowedHeaders: 'Content-Type,Authorization'
};
app.use(cors(corsOptions));

// 使用 Express 内置中间件解析 JSON 和 form 数据
app.use(express.json({ limit: '10kb' }));
app.use(express.urlencoded({ extended: true }));

// 文件上传配置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const uploadDir = path.join(__dirname, 'public', 'uploads');
        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir, { recursive: true });
        }
        cb(null, uploadDir);
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        const ext = path.extname(file.originalname);
        cb(null, file.fieldname + '-' + uniqueSuffix + ext);
    }
});

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 5 * 1024 * 1024 // 限制5MB
    }
});

// 创建日志目录
const logDir = path.join(__dirname, 'logs');
if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir);
}

// 日志文件路径
const accessLogPath = path.join(logDir, 'access.log');
const errorLogPath = path.join(logDir, 'error.log');
const dbLogPath = path.join(logDir, 'db.log');

// 日志轮换函数
const rotateLog = (logPath) => {
    try {
        // 检查日志文件是否存在
        if (!fs.existsSync(logPath)) {
            return;
        }

        // 获取文件大小（单位：字节）
        const stats = fs.statSync(logPath);
        const fileSizeInBytes = stats.size;

        // 如果文件大于5MB，执行日志轮换
        if (fileSizeInBytes > 5 * 1024 * 1024) {
            // 获取当前时间作为备份文件名后缀
            const timestamp = new Date().toISOString().replace(/:/g, '-');
            const backupPath = `${logPath}.${timestamp}`;

            // 重命名当前日志文件为备份文件
            fs.renameSync(logPath, backupPath);

            // 创建新的日志文件
            fs.writeFileSync(logPath, `[${new Date().toISOString()}] 日志文件已轮换，旧日志已保存到 ${backupPath}\n`);

            // 保留最近10个日志文件，删除旧的（跨平台兼容方式）
            const logDir = path.dirname(logPath);
            const baseFileName = path.basename(logPath);
            const pattern = new RegExp(`^${baseFileName}\\..*`);

            try {
                // 获取所有符合模式的轮换日志文件
                const files = fs.readdirSync(logDir)
                   .filter(file => pattern.test(file))
                   .map(file => ({
                        name: file,
                        path: path.join(logDir, file),
                        time: fs.statSync(path.join(logDir, file)).mtime.getTime()
                    }))
                   .sort((a, b) => b.time - a.time); // 按时间从新到旧排序

                // 保留最新的10个文件，删除其余的
                if (files.length > 10) {
                    const filesToDelete = files.slice(10);
                    for (const file of filesToDelete) {
                        try {
                            fs.unlinkSync(file.path);
                            console.log(`已删除旧日志文件: ${file.name}`);
                        } catch (err) {
                            console.error(`删除日志文件失败: ${file.path}`, err);
                        }
                    }
                }
            } catch (error) {
                console.error(`清理旧日志文件失败: ${error.message}`);
            }

            console.log(`日志已轮换: ${logPath} -> ${backupPath}`);
            return true;
        }

        return false;
    } catch (error) {
        console.error(`日志轮换错误: ${error.message}`);
        return false;
    }
};

// 每小时检查一次日志大小，必要时进行轮换
setInterval(() => {
    rotateLog(accessLogPath);
    rotateLog(errorLogPath);
    rotateLog(dbLogPath);
}, 3600000); // 3600000毫秒 = 1小时

// 启动时检查一次日志大小
rotateLog(accessLogPath);
rotateLog(errorLogPath);
rotateLog(dbLogPath);

// 创建日志文件流
const accessLogStream = fs.createWriteStream(accessLogPath, { flags: 'a' });
const errorLogStream = fs.createWriteStream(errorLogPath, { flags: 'a' });
const dbLogStream = fs.createWriteStream(dbLogPath, { flags: 'a' });

// 日志函数
const logToFile = (stream, message) => {
    const timestamp = new Date().toISOString();
    stream.write(`[${timestamp}] ${message}\n`);
};

// 请求日志中间件
app.use((req, res, next) => {
    const start = Date.now();
    const timestamp = new Date().toISOString();
    const logMessage = `[${timestamp}] ${req.method} ${req.url} 请求开始 - IP: ${req.ip}`;
    console.log(logMessage);
    logToFile(accessLogStream, logMessage);

    // 记录请求体，但排除敏感信息（如密码等）
    const requestBody = { ...req.body };
    if (requestBody.password) {
        requestBody.password = '********'; // 屏蔽密码
    }
    const requestBodyStr = JSON.stringify(requestBody);
    if (Object.keys(requestBody).length > 0) {
        logToFile(accessLogStream, `[${timestamp}] 请求体: ${requestBodyStr}`);
    }

    // 响应完成后记录
    res.on('finish', () => {
        const duration = Date.now() - start;
        const finishLog = `[${timestamp}] ${req.method} ${req.url} 请求完成 - 状态: ${res.statusCode} - 耗时: ${duration}ms`;
        console.log(finishLog);
        logToFile(accessLogStream, finishLog);
    });

    next();
});

// 设置静态文件目录
app.use(express.static('public'));

// 请求体解析错误处理
app.use((err, req, res, next) => {
    if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
        logToFile(errorLogStream, `JSON解析错误: ${err.message} - URL: ${req.url}`);
        return res.status(400).json({ success: false, message: '无效的JSON格式' });
    }
    next(err);
});

// 添加默认的查询参数处理中间件
app.use((req, res, next) => {
    // 确保查询参数存在
    req.query = req.query || {};

    // 确保请求体存在
    req.body = req.body || {};

    // 记录所有请求的参数，便于调试
    if (Object.keys(req.query).length > 0) {
        logToFile(accessLogStream, `请求查询参数: ${JSON.stringify(req.query)}`);
    }

    // 只记录非二进制的请求体
    if (req.method !== 'GET' && req.is('json') && Object.keys(req.body).length > 0) {
        // 避免记录敏感信息如密码
        const safeBody = { ...req.body };
        if (safeBody.password) safeBody.password = '******';
        logToFile(accessLogStream, `请求体: ${JSON.stringify(safeBody)}`);
    }

    next();
});

// 引入 mysql2 库
const mysql = require('mysql2');
// 配置数据库连接池
const pool = mysql.createPool({
    host: process.env.DB_HOST || '127.0.0.1',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || 'QiFeng1!',
    database: process.env.DB_NAME || 'qifeng',
    port: process.env.DB_PORT || 3306,
    waitForConnections: true,
    connectionLimit: 10,
    authPlugins: { mysql_native_password: () => require('mysql2/lib/auth-plugins/mysql_native_password') }
});

// 封装数据库查询函数，添加日志
const executeQuery = (sql, params = []) => {
    return new Promise((resolve, reject) => {
        logToFile(dbLogStream, `执行SQL: ${sql} 参数: ${JSON.stringify(params)}`);
        pool.query(sql, params, (err, results) => {
            if (err) {
                const errorMsg = `SQL错误: ${err.message} - SQL: ${sql} - 参数: ${JSON.stringify(params)}`;
                console.error(errorMsg);
                logToFile(errorLogStream, errorMsg);
                logToFile(dbLogStream, errorMsg);
                reject(err);
                return;
            }
            const successMsg = `SQL成功: ${sql} - 结果数量: ${Array.isArray(results) ? results.length : 1}`;
            logToFile(dbLogStream, successMsg);
            resolve(results);
        });
    });
};

// 测试数据库连接
pool.getConnection((err, connection) => {
    if (err) {
        const errorMsg = `数据库连接失败: ${err.message}`;
        console.error(errorMsg);
        logToFile(errorLogStream, errorMsg);
        logToFile(dbLogStream, errorMsg);
    } else {
        const successMsg = `数据库连接成功! 主机: ${process.env.DB_HOST}, 数据库: ${process.env.DB_NAME}`;
        console.log(successMsg);
        logToFile(dbLogStream, successMsg);
        connection.release();
    }
});

// 初始化数据库表结构
const initDatabase = () => {
    // 创建 users 表
    const createUsersTable = `
    CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(255) NOT NULL UNIQUE,
        password VARCHAR(255) NOT NULL,
        userNickname VARCHAR(255),
        level VARCHAR(50) DEFAULT '1',
        balance DECIMAL(10, 2) DEFAULT 0.00,
        userType VARCHAR(50) DEFAULT 'user',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )`;

    executeQuery(createUsersTable)
       .then(() => {
            console.log('Users table created or already exists');

            // 检查是否有管理员用户，如果没有则创建默认管理员
            const checkAdmin = `SELECT * FROM users WHERE username = 'qifeng'`;
            return executeQuery(checkAdmin);
        })
       .then(results => {
            if (results.length === 0) {
                // 创建默认管理员用户
                const saltRounds = 10;
                return bcrypt.hash('admin123', saltRounds)
                   .then(hash => {
                        const insertAdmin = `
                        INSERT INTO users (username, password, userNickname, level, balance, userType) 
                        VALUES (?, ?, ?, ?, ?, ?)`;
                        return executeQuery(insertAdmin, ['qifeng', hash, 'qifeng管理员', '10', 10000.00, 'admin']);
                    })
                   .then(() => {
                        console.log('Default admin user created: qifeng/admin123');
                    });
            }
        })
       .catch(err => {
            console.error('Error creating users table or admin user:', err);
        });

    // 创建 advertisements 表
    const createAdsTable = `
    CREATE TABLE IF NOT EXISTS advertisements (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        content TEXT,
        imageUrl VARCHAR(255),
        clickCount INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )`;

    executeQuery(createAdsTable)
       .then(() => {
            console.log('Advertisements table created or already exists');

            // 检查是否有广告，如果没有则添加示例广告
            const checkAds = `SELECT * FROM advertisements LIMIT 1`;
            return executeQuery(checkAds);
        })
       .then(results => {
            if (results.length === 0) {
                // 添加示例广告
                const insertAds = `
                INSERT INTO advertisements (title, content, imageUrl) VALUES 
                (?, ?, ?),
                (?, ?, ?),
                (?, ?, ?)`;
                const adsData = [
                    '限时活动', '新用户注册送20元', '<url id="cvfl655nfo2l158eks40" type="url" status="failed" title="" wc="0">https://via.placeholder.com/300</url> ',
                    '分享赚钱', '邀请好友双方各得10元', '<url id="cvfl655nfo2l158eks40" type="url" status="failed" title="" wc="0">https://via.placeholder.com/300</url> ',
                    '每日签到', '连续签到送大礼', '<url id="cvfl655nfo2l158eks40" type="url" status="failed" title="" wc="0">https://via.placeholder.com/300</url> '
                ];
                return executeQuery(insertAds, adsData)
                   .then(() => {
                        console.log('Sample advertisements created');
                    });
            }
        })
       .catch(err => {
            console.error('Error creating advertisements table or sample ads:', err);
        });

    // 创建 reward_tasks 表
    const createTasksTable = `
    CREATE TABLE IF NOT EXISTS reward_tasks (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        description TEXT,
        reward DECIMAL(10, 2) DEFAULT 0.00,
        imageUrl VARCHAR(255),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )`;

    executeQuery(createTasksTable)
       .then(() => {
            console.log('Reward tasks table created or already exists');

            // 检查是否有任务，如果没有则添加示例任务
            const checkTasks = `SELECT * FROM reward_tasks LIMIT 1`;
            return executeQuery(checkTasks);
        })
       .then(results => {
            if (results.length === 0) {
                // 添加示例任务
                const insertTasks = `
                INSERT INTO reward_tasks (title, description, reward, imageUrl) VALUES 
                (?, ?, ?, ?),
                (?, ?, ?, ?),
                (?, ?, ?, ?)`;
                const tasksData = [
                    '每日签到', '完成每日签到任务', 5.00, '<url id="cvfl655nfo2l158eks40" type="url" status="failed" title="" wc="0">https://via.placeholder.com/300</url> ',
                    '分享应用', '分享应用到社交媒体', 10.00, '<url id="cvfl655nfo2l158eks40" type="url" status="failed" title="" wc="0">https://via.placeholder.com/300</url> ',
                    '邀请好友', '成功邀请一位好友注册', 20.00, '<url id="cvfl655nfo2l158eks40" type="url" status="failed" title="" wc="0">https://via.placeholder.com/300</url> '
                ];
                return executeQuery(insertTasks, tasksData)
                   .then(() => {
                        console.log('Sample reward tasks created');
                    });
            }
        })
       .catch(err => {
            console.error('Error creating reward_tasks table or sample tasks:', err);
        });

    // 创建 user_task_status 表
    const createTaskStatusTable = `
    CREATE TABLE IF NOT EXISTS user_task_status (
        id INT AUTO_INCREMENT PRIMARY KEY,
        taskId INT NOT NULL,
        userId INT NOT NULL,
        status VARCHAR(50) DEFAULT 'pending',
        completedAt TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )`;

    executeQuery(createTaskStatusTable)
       .then(() => {
            console.log('User task status table created or already exists');
        })
       .catch(err => {
            console.error('Error creating user_task_status table:', err);
        });

    // 创建 projects 表
    const createProjectsTable = `
    CREATE TABLE IF NOT EXISTS projects (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        description TEXT,
        budget DECIMAL(10, 2) DEFAULT 0.00,
        status VARCHAR(50) DEFAULT 'open',
        imageUrl VARCHAR(255),
        owner_id INT,
        deadline VARCHAR(50),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )`;

    executeQuery(createProjectsTable)
       .then(() => {
            console.log('Projects table created or already exists');

            // 检查是否有项目，如果没有则添加示例项目
            const checkProjects = `SELECT * FROM projects LIMIT 1`;
            return executeQuery(checkProjects);
        })
       .then(results => {
            if (results.length === 0) {
                // 添加示例项目
                const insertProjects = `
                INSERT INTO projects (title, description, budget, imageUrl) VALUES 
                (?, ?, ?, ?),
                (?, ?, ?, ?),
                (?, ?, ?, ?)`;
                const projectsData = [
                    '电商网站开发', '开发一个电商网站，包括商品展示、购物车和支付功能', 50.00, '<url id="cvfl655nfo2l158eks40" type="url" status="failed" title="" wc="0">https://via.placeholder.com/300</url> ',
                    '社交媒体应用', '开发一个类似Instagram的社交媒体应用', 100.00, '<url id="cvfl655nfo2l158eks40" type="url" status="failed" title="" wc="0">https://via.placeholder.com/300</url> ',
                    '健身应用', '开发一个健身追踪应用，包括运动记录和饮食建议', 30.00, '<url id="cvfl655nfo2l158eks40" type="url" status="failed" title="" wc="0">https://via.placeholder.com/300</url> '
                ];
                return executeQuery(insertProjects, projectsData)
                   .then(() => {
                        console.log('Sample projects created');
                    });
            }
        })
       .catch(err => {
            console.error('Error creating projects table or sample projects:', err);
        });

    // 创建 user_invitations 表
    const createInvitationsTable = `
    CREATE TABLE IF NOT EXISTS invitations (
        id INT AUTO_INCREMENT PRIMARY KEY,
        inviter_id INT NOT NULL,
        invitee_id INT NOT NULL,
        level INT NOT NULL,
        status VARCHAR(20) DEFAULT 'active',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (inviter_id) REFERENCES users(id),
        FOREIGN KEY (invitee_id) REFERENCES users(id),
        UNIQUE KEY unique_invitation (inviter_id, invitee_id, level)
    )`;

    executeQuery(createInvitationsTable)
       .then(() => {
            console.log('Invitations table created or already exists');
            logToFile(dbLogStream, '邀请关系表创建成功或已存在');
        })
       .catch(err => {
            console.error('Error creating invitations table:', err);
            logToFile(errorLogStream, `创建invitations表失败: ${err.message}`);
        });

    // 创建邀请码表
    const createInviteCodesTable = `
    CREATE TABLE IF NOT EXISTS invite_codes (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        code VARCHAR(20) NOT NULL UNIQUE,
        is_used TINYINT(1) DEFAULT 0,
        used_by INT NULL,
        used_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id)
    )`;

    executeQuery(createInviteCodesTable)
       .then(() => {
            console.log('Invite codes table created or already exists');
            logToFile(dbLogStream, '邀请码表创建成功或已存在');
        })
       .catch(err => {
            console.error('Error creating invite_codes table:', err);
            logToFile(errorLogStream, `创建invite_codes表失败: ${err.message}`);
        });

    // 创建提现表
    const createWithdrawalsTable = `
    CREATE TABLE IF NOT EXISTS withdrawals (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        amount DECIMAL(10, 2) NOT NULL,
        status VARCHAR(20) DEFAULT 'pending',
        processed_at TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id)
    )`;

    executeQuery(createWithdrawalsTable)
       .then(() => {
            console.log('Withdrawals table created or already exists');
            logToFile(dbLogStream, '提现表创建成功或已存在');
        })
       .catch(err => {
            console.error('Error creating withdrawals table:', err);
            logToFile(errorLogStream, `创建withdrawals表失败: ${err.message}`);
        });

    // 创建余额变动日志表
    const createBalanceLogsTable = `
    CREATE TABLE IF NOT EXISTS balance_logs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        task_id INT NULL,
        withdrawal_id INT NULL,
        invitation_id INT NULL,
        amount DECIMAL(10, 2) NOT NULL,
        balance_before DECIMAL(10, 2) NOT NULL,
        balance_after DECIMAL(10, 2) NOT NULL,
        operation_type VARCHAR(20) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id)
    )`;

    executeQuery(createBalanceLogsTable)
       .then(() => {
            console.log('Balance logs table created or already exists');
            logToFile(dbLogStream, '余额变动日志表创建成功或已存在');
        })
       .catch(err => {
            console.error('Error creating balance_logs table:', err);
            logToFile(errorLogStream, `创建balance_logs表失败: ${err.message}`);
        });
};

// 初始化数据库
initDatabase();

// 首页路由
app.get('/', (req, res) => {
    logToFile(accessLogStream, `访问首页`);
    res.json({
        success: true,
        message: '欢迎使用 MyDy 后端服务 - 已适配宝塔面板',
        version: '1.0.0',
        status: 'running'
    });
});

// 健康检查端点
app.get('/health', (req, res) => {
    const uptime = process.uptime();
    const uptimeFormatted = `${Math.floor(uptime / 86400)}天 ${Math.floor((uptime % 86400) / 3600)}小时 ${Math.floor((uptime % 3600) / 60)}分钟 ${Math.floor(uptime % 60)}秒`;
    
    const memoryUsage = process.memoryUsage();
    const freemem = os.freemem() / 1024 / 1024;
    const totalmem = os.totalmem() / 1024 / 1024;
    
    const healthData = {
        status: 'online',
        timestamp: new Date().toISOString(),
        uptime: uptimeFormatted,
        memory: {
            rss: `${Math.round(memoryUsage.rss / 1024 / 1024 * 100) / 100} MB`,
            heapTotal: `${Math.round(memoryUsage.heapTotal / 1024 / 1024 * 100) / 100} MB`,
            heapUsed: `${Math.round(memoryUsage.heapUsed / 1024 / 1024 * 100) / 100} MB`,
            external: `${Math.round(memoryUsage.external / 1024 / 1024 * 100) / 100} MB`,
        },
        system: {
            platform: os.platform(),
            version: os.release(),
            freemem: `${Math.round(freemem * 100) / 100} MB`,
            totalmem: `${Math.round(totalmem * 100) / 100} MB`,
            cpus: os.cpus().length
        },
        environment: process.env.NODE_ENV
    };
    
    logToFile(accessLogStream, `健康检查请求 - 状态: ${healthData.status}`);
    res.json(healthData);
});

// 验证用户登录并生成JWT令牌
const generateJWT = (user) => {
    // 移除敏感信息
    const userData = {
        userId: user.id,
        username: user.username,
        userType: user.userType,
        userNickname: user.userNickname
    };

    // 生成JWT令牌
    return jwt.sign(userData, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
};

// API端点：用户登录
app.post('/user/login', (req, res) => {
    const { username, password } = req.body;

    console.log(`尝试登录: 用户名 ${username}`);
    logToFile(accessLogStream, `尝试登录: 用户名 ${username}`);

    // 验证必填字段
    if (!username || !password) {
        const errorMsg = `登录失败: 缺少必填字段 (username=${!!username}, password=${!!password})`;
        console.log(errorMsg);
        logToFile(errorLogStream, errorMsg);
        return res.status(400).json({
            success: false,
            message: '用户名和密码为必填项'
        });
    }

    // 查询用户
    const sql = `SELECT * FROM users WHERE username = ?`;
    console.log(`执行SQL查询: ${sql} 参数: [${username}]`);
    logToFile(dbLogStream, `执行SQL查询: ${sql} 参数: [${username}]`);

    executeQuery(sql, [username])
       .then(results => {
            if (results.length === 0) {
                const errorMsg = `登录失败: 用户名 ${username} 不存在`;
                console.log(errorMsg);
                logToFile(errorLogStream, errorMsg);
                return res.status(401).json({
                    success: false,
                    message: '用户名或密码错误'
                });
            }

            const user = results[0];
            console.log(`找到用户: ID=${user.id}, Type=${user.userType}`);

            // 使用 bcrypt 比较密码
            bcrypt.compare(password, user.password, (err, isMatch) => {
                if (err) {
                    const errorMsg = `密码比对错误: ${err.message}`;
                    console.error(errorMsg);
                    logToFile(errorLogStream, errorMsg);
                    return res.status(500).json({
                        success: false,
                        message: '登录过程中发生错误'
                    });
                }

                if (!isMatch) {
                    const errorMsg = `登录失败: 用户名 ${username} 密码错误`;
                    console.log(errorMsg);
                    logToFile(errorLogStream, errorMsg);
                    return res.status(401).json({
                        success: false,
                        message: '用户名或密码错误'
                    });
                }

                // 生成JWT令牌
                const token = generateJWT(user);
                console.log(`登录成功: 用户名 ${username}, 令牌生成`);

                // 返回用户信息和令牌
                res.json({
                    success: true,
                    message: '登录成功',
                    token: token,
                    userId: user.id,
                    username: user.username,
                    userType: user.userType || 'user',
                    userNickname: user.userNickname || user.username,
                    balance: user.balance || 0,
                    level: user.level || 'basic'
                });
            });
        })
       .catch(error => {
            const errorMsg = `登录查询失败: ${error.message}`;
            console.error(errorMsg);
            logToFile(errorLogStream, errorMsg);
            res.status(500).json({
                success: false,
                message: '登录失败',
                error: error.message
            });
        });
});

// 中间件：验证JWT令牌
const verifyToken = (req, res, next) => {
    const authHeader = req.headers.authorization;

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return res.status(401).json({
            success: false,
            message: '未提供有效的认证令牌'
        });
    }

    const token = authHeader.split(' ')[1];

    jwt.verify(token, JWT_SECRET, (err, decoded) => {
        if (err) {
            return res.status(401).json({
                success: false,
                message: '认证令牌无效或已过期'
            });
        }

        // 将解码后的用户信息添加到请求对象
        req.user = decoded;
        next();
    });
};

// API端点：获取用户信息
app.get('/user/info', verifyToken, (req, res) => {
    const userId = req.user.userId;

    // 查询用户信息
    const sql = `SELECT id, username, userNickname, level, balance, userType FROM users WHERE id = ?`;

    executeQuery(sql, [userId])
       .then(results => {
            if (results.length === 0) {
                return res.status(404).json({
                    success: false,
                    message: '未找到用户'
                });
            }

            const user = results[0];

            res.json({
                success: true,
                message: '获取用户信息成功',
                data: {
                    id: user.id,
                    username: user.username,
                    userNickname: user.userNickname,
                    level: user.level,
                    balance: user.balance,
                    userType: user.userType
                }
            });
        })
       .catch(error => {
            logToFile(errorLogStream, `获取用户信息失败: ${error.message}`);
            res.status(500).json({
                success: false,
                message: '获取用户信息失败',
                error: error.message
            });
        });
});

// 获取用户数据 - 移除离线功能
app.get('/users', verifyToken, (req, res) => {
    // 只允许管理员访问
    if (req.user.userType !== 'admin') {
        return res.status(403).json({ success: false, message: '权限不足' });
    }

    const username = req.query.username;
    const sql = username ? 'SELECT * FROM users WHERE username = ?' : 'SELECT * FROM users ORDER BY created_at DESC LIMIT 10';

    executeQuery(sql, [username])
       .then(results => {
            if (results.length === 0 && username) {
                return res.status(404).json({ success: false, message: '用户未找到' });
            }

            if (username) {
                const user = results[0];
                res.json({
                    id: user.id,
                    username: user.username,
                    userNickname: user.userNickname,
                    level: user.level,
                    balance: user.balance,
                    taskRewardToday: 0,
                    subTaskReward: 0,
                    inviteCount: 0,
                    taskCount: 0,
                    userBalance: user.balance
                });
            } else {
                const usersList = results.map(user => ({
                    id: user.id,
                    username: user.username,
                    userNickname: user.userNickname,
                    level: user.level,
                    userType: user.userType,
                    createdAt: user.created_at
                }));

                res.json({
                    success: true,
                    totalCount: results.length,
                    users: usersList
                });
            }
        })
       .catch(err => {
            console.error('获取用户数据错误:', err);
            logToFile(errorLogStream, `获取用户数据错误: ${err.message}`);
            res.status(500).json({ success: false, message: '服务器错误' });
        });
});

// 获取广告列表
app.get('/advertisements', (req, res) => {
    const sql = 'SELECT * FROM advertisements ORDER BY created_at DESC';
    executeQuery(sql)
       .then(results => {
            res.json({
                success: true,
                advertisements: results.map(ad => ({
                    id: ad.id,
                    title: ad.title,
                    content: ad.content,
                    imageUrl: ad.imageUrl,
                    clickCount: ad.clickCount,
                    createdAt: ad.created_at
                }))
            });
        })
       .catch(err => {
            console.error('获取广告列表错误:', err);
            res.status(500).json({ success: false, message: '服务器错误' });
        });
});

// 获取任务奖励
app.get('/tasks/reward', (req, res) => {
    const sql = 'SELECT * FROM reward_tasks ORDER BY created_at DESC';
    executeQuery(sql)
       .then(results => {
            res.json({
                success: true,
                tasks: results.map(task => ({
                    id: task.id,
                    title: task.title,
                    description: task.description,
                    reward: task.reward,
                    imageUrl: task.imageUrl
                }))
            });
        })
       .catch(err => {
            console.error('获取奖励任务错误:', err);
            logToFile(errorLogStream, `获取奖励任务错误: ${err.message}`);
            res.status(500).json({ success: false, message: '服务器错误' });
        });
});

// 获取用户任务状态 - 移除离线功能
app.get('/tasks/user/status', verifyToken, (req, res) => {
    const userId = req.user.userId;

    // 查询用户任务状态
    const getTaskStatusSql = `
        SELECT 
            uts.id, 
            uts.taskId, 
            uts.userId, 
            uts.status, 
            uts.completedAt, 
            rt.title, 
            rt.description, 
            rt.reward 
        FROM user_task_status uts 
        JOIN reward_tasks rt ON uts.taskId = rt.id 
        WHERE uts.userId = ? 
        ORDER BY uts.created_at DESC
    `;

    executeQuery(getTaskStatusSql, [userId])
        .then(taskStatusResults => {
            res.json({
                success: true,
                tasks: taskStatusResults.map(task => ({
                    taskId: task.taskId,
                    userId: task.userId,
                    status: task.status,
                    completedAt: task.completedAt,
                    title: task.title,
                    description: task.description,
                    reward: task.reward
                }))
            });
        })
        .catch(error => {
            console.error('获取用户任务状态错误:', error);
            logToFile(errorLogStream, `获取用户任务状态错误: ${error.message}`);
            res.status(500).json({ success: false, message: '服务器错误' });
        });
});

// 获取奖励信息 - 新增API
app.get('/rewards', (req, res) => {
    const sql = 'SELECT * FROM reward_tasks ORDER BY created_at DESC';
    executeQuery(sql)
        .then(results => {
            res.json({
                success: true,
                rewards: results.map(task => ({
                    id: task.id,
                    title: task.title,
                    description: task.description,
                    reward: task.reward,
                    imageUrl: task.imageUrl
                }))
            });
        })
        .catch(err => {
            console.error('获取奖励信息错误:', err);
            res.status(500).json({ success: false, message: '服务器错误' });
        });
});

// 获取项目信息 - 新增API
app.get('/projects', (req, res) => {
    const sql = 'SELECT * FROM projects ORDER BY created_at DESC';
    executeQuery(sql)
        .then(results => {
            res.json({
                success: true,
                projects: results.map(project => ({
                    id: project.id,
                    title: project.title,
                    description: project.description,
                    budget: project.budget,
                    status: project.status,
                    imageUrl: project.imageUrl
                }))
            });
        })
        .catch(err => {
            console.error('获取项目信息错误:', err);
            res.status(500).json({ success: false, message: '服务器错误' });
        });
});

// 添加服务器状态检查API路由 - 这个路由不需要验证
app.get('/api/status', (req, res) => {
    try {
        res.status(200).json({
            success: true,
            message: 'Server is running',
            timestamp: new Date().toISOString(),
            serverTime: new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }),
            status: 'online'
        });
    } catch (error) {
        console.error('服务器状态检查错误:', error);
        res.status(500).json({ 
            success: false, 
            message: '服务器状态检查错误',
            error: error.message
        });
    }
});

// 查看日志API - 仅管理员可访问
app.get('/api/logs/:type', verifyToken, (req, res) => {
    if (req.user.userType !== 'admin') {
        return res.status(403).json({ success: false, message: '权限不足' });
    }

    const logType = req.params.type;
    const logFiles = {
        access: accessLogPath,
        error: errorLogPath,
        db: dbLogPath
    };

    if (!logFiles[logType]) {
        return res.status(400).json({ success: false, message: '无效的日志类型' });
    }

    exec(`tail -n 200 ${logFiles[logType]}`, (error, stdout) => {
        if (error) {
            logToFile(errorLogStream, `读取日志文件失败: ${error.message}`);
            return res.status(500).json({ success: false, message: '读取日志失败' });
        }

        res.json({ 
            success: true, 
            logType: logType,
            lines: stdout.split('\n').filter(Boolean)
        });
    });
});

// 日志统计API - 仅管理员可访问
app.get('/api/logs/stats', verifyToken, (req, res) => {
    if (req.user.userType !== 'admin') {
        return res.status(403).json({ success: false, message: '权限不足' });
    }

    const getLogStats = (logPath) => {
        return new Promise((resolve) => {
            fs.stat(logPath, (err, stats) => {
                resolve({
                    size: stats.size,
                    lines: require('fs').readFileSync(logPath, 'utf8').split('\n').length - 1
                });
            });
        });
    };

    Promise.all([
        getLogStats(accessLogPath),
        getLogStats(errorLogPath),
        getLogStats(dbLogPath)
    ]).then(stats => {
        res.json({
            success: true,
            access: stats[0],
            error: stats[1],
            db: stats[2]
        });
    }).catch(err => {
        res.status(500).json({ success: false, message: '获取日志统计失败' });
    });
});

// API端点：获取任务列表
app.get('/task/list', verifyToken, (req, res) => {
    const sql = 'SELECT * FROM reward_tasks ORDER BY created_at DESC';
    executeQuery(sql)
        .then(tasks => res.json({ success: true, data: tasks }))
        .catch(error => res.status(500).json({ success: false, error: error.message }));
});

// API端点：获取任务详情
app.get('/task/:id', verifyToken, (req, res) => {
    const taskId = req.params.id;
    const sql = 'SELECT * FROM reward_tasks WHERE id = ?';
    executeQuery(sql, [taskId])
        .then(results => results.length ? res.json({ success: true, data: results[0] }) : res.status(404).json({ success: false, message: '任务未找到' }))
        .catch(error => res.status(500).json({ success: false, error: error.message }));
});

// API端点：提交任务
app.post('/task/submit', upload.single('proof'), verifyToken, (req, res) => {
    const { taskId, description } = req.body;
    if (!taskId || !description) {
        return res.status(400).json({ success: false, message: '任务ID和描述为必填项' });
    }

    const proofUrl = req.file ? `/uploads/${req.file.filename}` : null;
    const sql = `
        INSERT INTO task_submissions (userId, taskId, description, proofUrl, status)
        VALUES (?, ?, ?, ?, 'pending')
    `;

    executeQuery(sql, [req.user.userId, taskId, description, proofUrl])
        .then(() => res.json({ success: true, message: '任务提交成功' }))
        .catch(error => res.status(500).json({ success: false, error: error.message }));
});

// =============== 项目相关API ===============
app.get('/project/list', verifyToken, (req, res) => {
    const sql = 'SELECT * FROM projects ORDER BY created_at DESC';
    executeQuery(sql)
        .then(results => res.json({ success: true, data: results }))
        .catch(error => res.status(500).json({ success: false, error: error.message }));
});

app.get('/project/:id', verifyToken, (req, res) => {
    const projectId = req.params.id;
    const sql = `
        SELECT p.*, u.username AS ownerUsername 
        FROM projects p 
        LEFT JOIN users u ON p.owner_id = u.id 
        WHERE p.id = ?
    `;

    executeQuery(sql, [projectId])
        .then(results => {
            if (results.length === 0) return res.status(404).json({ success: false, message: '项目未找到' });
            
            res.json({
                success: true,
                data: results[0]
            });
        })
        .catch(error => res.status(500).json({ success: false, error: error.message }));
});

// 管理员添加项目
app.post('/admin/project/add', verifyToken, (req, res) => {
    if (req.user.userType !== 'admin') {
        return res.status(403).json({ success: false, message: '需要管理员权限' });
    }

    const { title, description, budget, imageUrl, deadline } = req.body;
    if (!title || !description || !budget) {
        return res.status(400).json({ success: false, message: '标题、描述和预算为必填项' });
    }

    const sql = `
        INSERT INTO projects (title, description, budget, imageUrl, deadline, owner_id)
        VALUES (?, ?, ?, ?, ?, ?)
    `;

    executeQuery(sql, [title, description, budget, imageUrl, deadline, req.user.userId])
        .then(result => res.json({ success: true, projectId: result.insertId }))
        .catch(error => res.status(500).json({ success: false, error: error.message }));
});

// =============== 邀请相关API ===============
function generateInviteCode(userId) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let code = userId.toString(36).toUpperCase();
    while (code.length < 6) code = chars[Math.floor(Math.random() * chars.length)] + code;
    return code;
}

// 获取邀请码API
app.get('/user/invite/code', verifyToken, (req, res) => {
    const sql = `
        SELECT code FROM invite_codes 
        WHERE user_id = ? AND is_used = 0
        LIMIT 1
    `;

    executeQuery(sql, [req.user.userId])
        .then(results => {
            if (results.length > 0) {
                return res.json({ success: true, inviteCode: results[0].code });
            }

            const code = generateInviteCode(req.user.userId);
            const insertSql = 'INSERT INTO invite_codes (user_id, code) VALUES (?, ?)';
            return executeQuery(insertSql, [req.user.userId, code])
                .then(() => res.json({ success: true, inviteCode: code }));
        })
        .catch(error => {
            logToFile(errorLogStream, `获取邀请码错误: ${error.message}`);
            res.status(500).json({ success: false, message: '获取邀请码失败', error: error.message });
        });
});

// 生成新邀请码API
app.post('/user/invite/generate', verifyToken, (req, res) => {
    const code = generateInviteCode(req.user.userId);
    const insertSql = 'INSERT INTO invite_codes (user_id, code) VALUES (?, ?)';
    
    executeQuery(insertSql, [req.user.userId, code])
        .then(() => {
            logToFile(accessLogStream, `用户 ${req.user.username} 生成了新邀请码: ${code}`);
            res.json({ success: true, inviteCode: code });
        })
        .catch(error => {
            logToFile(errorLogStream, `生成邀请码错误: ${error.message}`);
            res.status(500).json({ success: false, message: '生成邀请码失败', error: error.message });
        });
});

// 使用邀请码API
app.post('/user/invite/use', verifyToken, (req, res) => {
    const { inviteCode } = req.body;
    
    if (!inviteCode) {
        return res.status(400).json({ success: false, message: '邀请码不能为空' });
    }
    
    // 查询邀请码是否有效
    const checkCodeSql = `SELECT id, user_id FROM invite_codes WHERE code = ? AND is_used = 0`;
    
    executeQuery(checkCodeSql, [inviteCode])
        .then(results => {
            if (results.length === 0) {
                return res.status(400).json({ success: false, message: '邀请码无效或已被使用' });
            }
            
            const inviteCodeId = results[0].id;
            const inviterId = results[0].user_id;
            
            // 检查是否是自己的邀请码
            if (inviterId === req.user.userId) {
                return res.status(400).json({ success: false, message: '不能使用自己的邀请码' });
            }
            
            // 开始事务
            return executeQuery('START TRANSACTION')
                .then(() => {
                    // 更新邀请码为已使用
                    const updateCodeSql = `
                        UPDATE invite_codes 
                        SET is_used = 1, used_by = ?, used_at = NOW() 
                        WHERE id = ?
                    `;
                    
                    return executeQuery(updateCodeSql, [req.user.userId, inviteCodeId])
                        .then(() => {
                            // 添加邀请关系
                            const insertRelationSql = `
                                INSERT INTO invitations (inviter_id, invitee_id, level, created_at)
                                VALUES (?, ?, 1, NOW())
                            `;
                            
                            return executeQuery(insertRelationSql, [inviterId, req.user.userId])
                                .then(() => {
                                    // 提交事务
                                    return executeQuery('COMMIT')
                                        .then(() => {
                                            logToFile(accessLogStream, `用户 ${req.user.username} 使用了邀请码 ${inviteCode}`);
                                            res.json({ success: true, message: '成功使用邀请码' });
                                        });
                                });
                        });
                })
                .catch(error => {
                    // 回滚事务
                    executeQuery('ROLLBACK');
                    throw error;
                });
        })
        .catch(error => {
            logToFile(errorLogStream, `使用邀请码错误: ${error.message}`);
            res.status(500).json({ success: false, message: '处理邀请码失败', error: error.message });
        });
});

// 获取邀请记录API
app.get('/user/invitations', verifyToken, (req, res) => {
    const sql = `
        SELECT 
            i.level, 
            u.username, 
            u.userNickname, 
            u.created_at AS registeredAt 
        FROM invitations i 
        JOIN users u ON i.invitee_id = u.id 
        WHERE i.inviter_id = ? 
        ORDER BY i.level, u.created_at DESC
    `;

    executeQuery(sql, [req.user.userId])
        .then(results => {
            const grouped = results.reduce((acc, curr) => {
                if (!acc[curr.level]) acc[curr.level] = [];
                acc[curr.level].push(curr);
                return acc;
            }, { 1: [], 2: [], 3: [] });

            res.json({
                success: true,
                levels: {
                    1: grouped[1],
                    2: grouped[2],
                    3: grouped[3]
                }
            });
        })
        .catch(error => res.status(500).json({ success: false, error: error.message }));
});

// 用户提现相关API
app.post('/user/withdrawal', verifyToken, (req, res) => {
    const { amount } = req.body;
    if (isNaN(amount) || amount <= 0) {
        return res.status(400).json({ success: false, message: '请输入有效的提现金额' });
    }

    const sql = `
        START TRANSACTION;
        UPDATE users SET balance = balance - ? WHERE id = ?;
        INSERT INTO withdrawals (user_id, amount) VALUES (?, ?);
        COMMIT;
    `;

    executeQuery(sql, [amount, req.user.userId, req.user.userId, amount])
        .then(() => res.json({ success: true, message: '提现申请已提交' }))
        .catch(error => {
            executeQuery('ROLLBACK');
            res.status(500).json({ success: false, error: error.message });
        });
});

// 获取用户余额API
app.get('/user/balance', verifyToken, (req, res) => {
    const sql = 'SELECT balance FROM users WHERE id = ?';
    executeQuery(sql, [req.user.userId])
        .then(results => res.json({ success: true, balance: results[0].balance }))
        .catch(error => res.status(500).json({ success: false, error: error.message }));
});

// 添加状态检查路由
app.get('/status', verifyToken, (req, res) => {
    // 只允许管理员用户访问
    if (req.user.role !== 'admin') {
        return res.status(403).json({ success: false, message: '权限不足' });
    }
    
    // 收集系统状态信息
    const serverTime = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
    let dbStatus = 'unknown';
    
    // 执行测试查询检查数据库连接
    executeQuery('SELECT 1 AS test_connection')
        .then(result => {
            dbStatus = result ? 'connected' : 'error';
            
            res.json({
                success: true,
                serverTime,
                serverStatus: 'running',
                dbStatus,
                nodeVersion: process.version,
                uptime: `${Math.floor(process.uptime() / 60)} 分钟`,
                memoryUsage: `${Math.round(process.memoryUsage().rss / 1024 / 1024)} MB`,
                environment: process.env.NODE_ENV
            });
        })
        .catch(err => {
            logToFile(errorLogStream, `数据库状态检查失败: ${err.message}`);
            dbStatus = 'disconnected';
            
            res.json({
                success: true,
                serverTime,
                serverStatus: 'running',
                dbStatus,
                nodeVersion: process.version,
                uptime: `${Math.floor(process.uptime() / 60)} 分钟`,
                memoryUsage: `${Math.round(process.memoryUsage().rss / 1024 / 1024)} MB`,
                environment: process.env.NODE_ENV,
                dbError: err.message
            });
        });
});

// 全局错误处理中间件
app.use((err, req, res, next) => {
    console.error('全局错误:', err.stack);
    logToFile(errorLogStream, `全局错误: ${err.message} - ${req.url}`);
    res.status(500).json({ success: false, message: '服务器内部错误' });
});

// 用户注册 - 普通注册
app.post('/user/register', (req, res) => {
    const { username, password, nickname } = req.body;
    
    // 验证输入
    if (!username || !password || !nickname) {
        return res.status(400).json({ 
            success: false, 
            message: '用户名、密码和昵称不能为空' 
        });
    }
    
    // 检查用户名是否已存在
    executeQuery('SELECT id FROM users WHERE username = ?', [username])
        .then(results => {
            if (results.length > 0) {
                return res.status(409).json({ 
                    success: false, 
                    message: '用户名已被注册' 
                });
            }
            
            // 生成盐和哈希密码
            const saltRounds = 10;
            bcrypt.hash(password, saltRounds, (err, hashedPassword) => {
                if (err) {
                    logToFile(errorLogStream, `密码哈希错误: ${err.message}`);
                    return res.status(500).json({ 
                        success: false, 
                        message: '注册处理失败，请稍后重试' 
                    });
                }
                
                // 插入新用户
                const sql = `
                    INSERT INTO users 
                    (username, password, userNickname, level, userType, created_at) 
                    VALUES (?, ?, ?, 1, 'user', NOW())
                `;
                
                executeQuery(sql, [username, hashedPassword, nickname])
                    .then(result => {
                        logToFile(accessLogStream, `新用户注册成功: ${username}`);
                        res.status(201).json({ 
                            success: true, 
                            message: '注册成功',
                            userId: result.insertId
                        });
                    })
                    .catch(error => {
                        logToFile(errorLogStream, `用户注册数据库错误: ${error.message}`);
                        res.status(500).json({ 
                            success: false, 
                            message: '注册失败，请稍后重试' 
                        });
                    });
            });
        })
        .catch(error => {
            logToFile(errorLogStream, `用户注册检查错误: ${error.message}`);
            res.status(500).json({ 
                success: false, 
                message: '注册失败，请稍后重试' 
            });
        });
});

// 带邀请码的用户注册
app.post('/user/register-with-invite', (req, res) => {
    const { username, password, userNickname, inviteCode } = req.body;
    
    // 验证输入
    if (!username || !password || !userNickname || !inviteCode) {
        return res.status(400).json({ 
            success: false, 
            message: '所有字段都是必填的' 
        });
    }
    
    // 首先验证邀请码是否有效
    executeQuery('SELECT user_id FROM invite_codes WHERE code = ? AND is_used = 0', [inviteCode])
        .then(inviteResults => {
            if (inviteResults.length === 0) {
                return res.status(400).json({ 
                    success: false, 
                    message: '邀请码无效或已被使用' 
                });
            }
            
            const inviterId = inviteResults[0].user_id;
            
            // 检查用户名是否已存在
            return executeQuery('SELECT id FROM users WHERE username = ?', [username])
                .then(userResults => {
                    if (userResults.length > 0) {
                        return res.status(409).json({ 
                            success: false, 
                            message: '用户名已被注册' 
                        });
                    }
                    
                    // 开始事务
                    return executeQuery('START TRANSACTION')
                        .then(() => {
                            // 生成盐和哈希密码
                            const saltRounds = 10;
                            return new Promise((resolve, reject) => {
                                bcrypt.hash(password, saltRounds, (err, hashedPassword) => {
                                    if (err) {
                                        reject(new Error(`密码哈希错误: ${err.message}`));
                                        return;
                                    }
                                    resolve(hashedPassword);
                                });
                            }).then(hashedPassword => {
                                // 插入新用户
                                const insertUserSql = `
                                    INSERT INTO users 
                                    (username, password, userNickname, level, userType, inviter_id, created_at) 
                                    VALUES (?, ?, ?, 1, 'user', ?, NOW())
                                `;
                                
                                return executeQuery(insertUserSql, [username, hashedPassword, userNickname, inviterId])
                                    .then(userInsertResult => {
                                        const newUserId = userInsertResult.insertId;
                                        
                                        // 更新邀请码为已使用
                                        const updateInviteCodeSql = `
                                            UPDATE invite_codes 
                                            SET is_used = 1, used_by = ?, used_at = NOW() 
                                            WHERE code = ?
                                        `;
                                        
                                        return executeQuery(updateInviteCodeSql, [newUserId, inviteCode])
                                            .then(() => {
                                                // 记录邀请关系
                                                const insertInvitationSql = `
                                                    INSERT INTO invitations 
                                                    (inviter_id, invitee_id, level, created_at) 
                                                    VALUES (?, ?, 1, NOW())
                                                `;
                                                
                                                return executeQuery(insertInvitationSql, [inviterId, newUserId])
                                                    .then(() => {
                                                        // 提交事务
                                                        return executeQuery('COMMIT')
                                                            .then(() => {
                                                                logToFile(accessLogStream, `新用户通过邀请码注册成功: ${username}, 邀请人ID: ${inviterId}`);
                                                                res.status(201).json({ 
                                                                    success: true, 
                                                                    message: '注册成功',
                                                                    userId: newUserId
                                                                });
                                                            });
                                                    });
                                            });
                                    });
                            });
                        })
                        .catch(error => {
                            // 回滚事务
                            executeQuery('ROLLBACK');
                            throw error;
                        });
                });
        })
        .catch(error => {
            logToFile(errorLogStream, `带邀请码注册错误: ${error.message}`);
            res.status(500).json({ 
                success: false, 
                message: '注册失败，请稍后重试' 
            });
        });
});

// 启动服务器
app.listen(port, host, () => {
    const serverUrl = `http://${host === '0.0.0.0' ? 'localhost' : host}:${port}`;
    const timestamp = new Date().toISOString();
    const startupMessage = `[${timestamp}] MyDy后端服务已启动，运行环境: ${process.env.NODE_ENV}, 服务地址: ${serverUrl}`;
    
    console.log('=========================================');
    console.log('🚀 MyDy后端服务已成功启动!');
    console.log(`📡 访问地址: ${serverUrl}`);
    console.log(`🔒 环境模式: ${process.env.NODE_ENV}`);
    console.log('=========================================');
    
    logToFile(accessLogStream, startupMessage);
    
    // 优雅关闭数据库连接
    process.on('SIGINT', () => {
        pool.end(() => {
            console.log('数据库连接已关闭');
            process.exit(0);
        });
    });
});